var websocket = null;
var websocketIsOpen=false;
var websocketID=(new Date()).getTime();
//生成随机串
//创建socket连接
function openWebSocket(){
    var text = document.getElementById('text').value;
    if(text!=null && text!=""){
        //var socketIDAndFunctionName=websocketID+"@"+text;
        var socketIDAndFunctionName=text;
        //判断当前浏览器是否支持WebSocket，支持就创建连接，不支持就提示
        if(isSupportWebSocket(socketIDAndFunctionName)){
            listenerWebSocket();
            //showWebSocketInfo();
        }
    }else{
        alert("请输入参数！");
    }

}

//监听websocket的回调方法
function listenerWebSocket(){
    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误!");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        //setMessageInnerHTML("WebSocket连接成功");
        websocket.send("socket-"+websocketID+"建立连接成功，测试消息。。。");
        websocketIsOpen=true;
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭!");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }
}

function showWebSocketInfo(){
    if(websocket!=null){
        setMessageInnerHTML("websocket="+JSON.stringify(websocket));
        setMessageInnerHTML("CONNECTING="+websocket.CONNECTING);//0
        setMessageInnerHTML("OPEN="+websocket.OPEN); //1
        setMessageInnerHTML("CLOSING="+websocket.CLOSING); //2
        setMessageInnerHTML("CLOSED="+websocket.CLOSED); //3
    }
}

//判断当前浏览器是否支持WebSocket
function isSupportWebSocket(socketIDAndFunctionName){
    if ('WebSocket' in window) {
        websocket = new WebSocket('ws://127.0.0.1:8081/websocket/mysocket?'+socketIDAndFunctionName);
        return true;
    }else {
        alert('当前浏览器 不支持websocket');
        return false;
    }
}

//将消息显示在网页上
function setMessageInnerHTML(innerHTML){
    //document.getElementById('message').value += innerHTML + '<br/>';
    document.getElementById('message').innerHTML+= innerHTML + '<br/>';
}
//关闭socket
function closeWebSocket() {
    if(websocket!=null && websocketIsOpen){
        websocket.close();
        //showWebSocketInfo();
        websocket=null;
        websocketIsOpen=false;
        websocketID=(new Date()).getTime();
    }
    setMessageInnerHTML("websocket已关闭！");
}
//清空message
function clearMessage(){
    //document.getElementById('message').value="";
    document.getElementById('message').innerHTML="";
    setMessageInnerHTML("清空message！");
}

//发送消息
function sendMessage() {
    var message = document.getElementById('text').value;
    if(websocketIsOpen){//如果socket开启
        websocket.send(message);
    }else{
        setMessageInnerHTML("websocket未创建或已关闭，请先开启连接！");
    }
}